import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { TreeNode } from '@iux/live';

@Component({
  selector: 'app-demo12',
  templateUrl: './demo12.component.html',
})
export class Demo12Component implements OnInit {
  data: TreeNode[];
  index = 5;

  constructor(
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnInit() {
    this.data = this.initAsync();
  }

  initAsync(len: number = 100, index: number = 0) {
    return Array.from({ length: len }).map((item, key) => {
      const node = this.initNode(key + index);
      return node;
    });
  }

  initNode(key: number): TreeNode {
    return {
      label: `user${key}`,
      key: `user${key}`,
      expanded: false,
      children: [],
      isLeaf: false,
      indeterminate: false,
    };
  }

  expandedChange(node) {
    const offsetIndex = 5;
    setTimeout(() => {
      if (!node.children?.length) {
        node.children = [...this.initAsync(offsetIndex, this.index)];
      }
      this.data = [...this.data];
      this.index += offsetIndex;
      this.cdr.markForCheck();
    }, 200);
  }
}
